package com.weiaibenpao.demo.chislim.ui.widget;

import android.content.Context;
import android.graphics.Typeface;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.support.annotation.RequiresApi;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.orhanobut.logger.Logger;
import com.weiaibenpao.demo.chislim.R;
import com.weiaibenpao.demo.chislim.service.RunningService;

import java.text.DecimalFormat;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by ZJL on 2017/12/19.
 */

public class RunningDataView extends RelativeLayout {
    @BindView(R.id.root)
    RelativeLayout root;
    @BindView(R.id.switch_container)
    RelativeLayout switchContainer;
    @BindView(R.id.left_image)
    ImageView leftTitleImage;
    @BindView(R.id.right_image)
    ImageView rightTitleImage;
    @BindView(R.id.iv_pause)
    ImageView ivPause;
    @BindView(R.id.iv_continue)
    ImageView ivContinue;
    @BindView(R.id.btn_finish)
    LongClickToFinishView btnFinish;
//    @BindView(R.id.iv_end)
//    ImageView ivEnd;
    @BindView(R.id.slideUnlockView)
    SlideUnlockView slideUnlockView;
    @BindView(R.id.mask)
    View mask;
    @BindView(R.id.tv_distance)
    TextView tvDistance;
    @BindView(R.id.tv_pace)
    TextView tvPace;
    @BindView(R.id.tv_time)
    TextView tvTime;
    @BindView(R.id.tv_calorie)
    TextView tvCalorie;
    public static final int RUNNING = 1;
    public static final int PAUSE = 2;
    private static final int MAX_PROGRESS = 100;
    private static final String TAG ="RunningDataView";
    private DecimalFormat decimalFormat = new DecimalFormat("0.00");
    private Handler mHandler  = new Handler(Looper.getMainLooper());
    private boolean mIsPressed;
    private int mCurrentProgress;



    public RunningDataView(Context context) {
//        super(context);
        this(context, null);
    }

    public RunningDataView(Context context, AttributeSet attrs) {
//        super(context, attrs);
        this(context, attrs, 0);
    }

    public RunningDataView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context);
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    public RunningDataView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
        init(context);
    }

    private void init(Context context) {
        View view = LayoutInflater.from(context).inflate(R.layout.layout_running_data, this);
        ButterKnife.bind(this, view);
        initLockView();
        initTextFonts();
        initLongClickToFinishView();
    }

    private void initLongClickToFinishView() {
        btnFinish.setOnTouchListener(new OnTouchListener() {

            @Override
            public boolean onTouch(View view, MotionEvent event) {

                switch (event.getAction()) {// 返回true的话，单击事件、长按事件不可以被触发
                    case MotionEvent.ACTION_DOWN:
                        mIsPressed = true;
                        mCurrentProgress = 0;
                        setProgress();
                        return true;
                    case MotionEvent.ACTION_UP:
                        mIsPressed = false;
                        break;
                    default:
                        break;
                }
                return false;
            }
        });
    }

    private void initTextFonts() {
        Typeface typeFace = Typeface.createFromAsset(getContext().getAssets(), "fonts/Reducto Condensed SSi Condensed.ttf");
        tvDistance.setTypeface(typeFace);
        tvPace.setTypeface(typeFace);
        tvTime.setTypeface(typeFace);
        tvCalorie.setTypeface(typeFace);

    }

    private void initLockView() {
        slideUnlockView.setOnUnLockListener(new SlideUnlockView.OnUnLockListener() {
            @Override
            public void setUnLocked(boolean unLocked) {
                if (unLocked) {
//                    root.setClickable(false);
                    rightTitleImage.setVisibility(VISIBLE);
                    mask.setVisibility(GONE);
                    slideUnlockView.reset();
                    slideUnlockView.setVisibility(View.GONE);
                    switchContainer.setVisibility(View.VISIBLE);
                }
            }
        });
    }


    public void setData(Bundle data) {
        if (data == null) return;
        Float distance = data.getFloat(RunningService.DISTANCE);
        String formatDis = decimalFormat.format(distance / 1000);
        tvDistance.setText(formatDis);
        tvPace.setText(data.getString(RunningService.PACE));
        tvCalorie.setText(data.getString(RunningService.CALORIE));
    }

    public void setTime(String runningTime) {
        tvTime.setText(runningTime);
    }

    public void setMapIconVisibility(int visibility){//常规室内没有地图，因而没有地图图标
        leftTitleImage.setVisibility(visibility);
    }

    @OnClick({R.id.left_image, R.id.right_image, R.id.iv_pause, R.id.iv_continue})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.left_image:
                Logger.e(TAG+"--on click map ");
                if (onUserActionListener != null) {
                    onUserActionListener.onClickShowMap();
                }
                break;
            case R.id.right_image:
                Logger.e(TAG+"--on click lock ");
                rightTitleImage.setVisibility(INVISIBLE);
                mask.setVisibility(VISIBLE);
                slideUnlockView.setVisibility(VISIBLE);
                switchContainer.setVisibility(GONE);
//                root.setClickable(true);
                break;
            case R.id.iv_pause:
                setState(PAUSE);
                if (onUserActionListener != null) {
                    onUserActionListener.onClickPause();
                }
                break;
            case R.id.iv_continue:
                setState(RUNNING);
                if (onUserActionListener != null) {
                    onUserActionListener.onClickContinue();
                }
                break;
//            case R.id.iv_end:
//                if (onUserActionListener != null) {
//                    onUserActionListener.onEndRunning();
//                }
//                break;
        }
    }

    public void setState(int  state) {
        int pauseVisibility ,otherVisibility ;
        if(PAUSE == state){
            pauseVisibility = GONE;
            otherVisibility = VISIBLE;
        }else {
            pauseVisibility = VISIBLE;
            otherVisibility = GONE;
        }
        ivPause.setVisibility(pauseVisibility);
        ivContinue.setVisibility(otherVisibility);
        btnFinish.setVisibility(otherVisibility);
//        ivEnd.setVisibility(otherVisibility);
    }


    private void setProgress() {
        mHandler.post(new Runnable() {
            @Override
            public void run() {
                if (mCurrentProgress < MAX_PROGRESS) {
                    if (mIsPressed) {// 一直长按
                        mCurrentProgress += 2;
                        mHandler.postDelayed(this, 20);
                        btnFinish.setProgress(mCurrentProgress);
                        Logger.e("setProgress setProgress-->"+mCurrentProgress);
                    } else {// 中途放弃长按
                        if (mCurrentProgress >= 50) {// 进度超过50%直接走到100%，
                            mCurrentProgress += 2;
                            mHandler.postDelayed(this, 20);
                            btnFinish.setProgress(mCurrentProgress);
                        } else {// 进度没到50%重置为0
                            mCurrentProgress = 0;
                            btnFinish.setProgress(mCurrentProgress);
                        }
                    }
                }else {
                    if(onUserActionListener != null){
                        onUserActionListener.onEndRunning();
                    }
                }
            }
        });
    }


    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        if(mHandler != null) mHandler.removeCallbacksAndMessages(null);
    }

    private OnUserActionListener onUserActionListener;

    public void setOnUserActionListener(OnUserActionListener listener) {
        onUserActionListener = listener;
    }

    public interface OnUserActionListener {

        void onClickShowMap();

        void onClickPause();

        void onClickContinue();

        void onEndRunning();

    }

}
